<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="about">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <div>选择发送者:</div>
        <a-select
            v-model:value="selectedSenderId"
            placeholder="选择发送者"
            style="width: 200px;"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="user in userOptions" :key="user.value" :value="user.value">
            {{ user.label }}
          </a-select-option>
        </a-select>
        <div>选择接收者:</div>
        <a-select
            v-model:value="selectedReceiverId"
            placeholder="选择接收者"
            style="width: 200px;"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option v-for="user in userOptions" :key="user.value" :value="user.value">
            {{ user.label }}
          </a-select-option>
        </a-select>
        <a-button type="primary" @click="handleFilter">检索</a-button>
        <a-button @click="resetFilter">重置</a-button>
        <a-button type="primary" @click="addMessage">
          新增
        </a-button>
      </a-space>
      <a-table :columns="columns" :row-key="item => item.messageId" :data-source="messages" :pagination="pagination"
               :loading="isLoading" @change="handleTableChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'content'">
            <span>{{ record.content }}</span>
          </template>
          <template v-if="column.dataIndex === 'isRead'">
            <span>{{ record.isRead ? '已读' : '未读' }}</span>
          </template>
          <template v-if="column.dataIndex === 'sentAt'">
            <span>{{ formatDate(record.sentAt) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary"
                        @click="showModal(record)"
              >
                编辑
              </a-button>
              <a-popconfirm
                  title="是否确认要删除?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteMessage(record)"
              >
                <a-button danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>
  <!-- 模态框 更新-->
  <a-modal v-model:open="open" title="编辑消息" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form ref="editForm" :model="MessageDis" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="发送者" name="senderId">
        <a-select v-model:value="MessageDis.senderId" :options="userOptions" placeholder="请选择发送者" />
      </a-form-item>
      <a-form-item label="接收者" name="receiverId">
        <a-select v-model:value="MessageDis.receiverId" :options="userOptions" placeholder="请选择接收者" />
      </a-form-item>
      <a-form-item label="职位" name="jobId">
        <a-select v-model:value="MessageDis.jobId" :options="jobOptions" placeholder="请选择职位" />
      </a-form-item>
      <a-form-item label="内容" name="content">
        <a-textarea v-model:value="MessageDis.content" />
      </a-form-item>
      <a-form-item label="是否已读" name="isRead">
        <a-switch v-model:checked="MessageDis.isRead" />
      </a-form-item>
      <a-form-item label="发送时间">
        <a-date-picker v-model:value="MessageDis.sentAt" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, ref} from 'vue';
import axios from 'axios';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
/* eslint-disable */
const open = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
// 表格数据
const messages = ref<Message[]>([]);
interface Pagination {
  current: number;
  pageSize: number;
  total?: number;
  [key: string]: any; // 可选扩展字段
}

// 分页信息
const pagination = ref({
  pageSize: 10, // 设置每页显示10条数据
  total: 0,
  current: 1
});
// 数据加载状态
const isLoading = ref(true);
// 是否搜索状态
const isSearch = ref(false);
// 日期格式化函数
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};
// 新增：发送者和接收者筛选条件
const selectedSenderId = ref<number | ''>('');
const selectedReceiverId = ref<number | ''>('');

// 新增：计算属性，用于前端筛选
// const filteredMessages = computed(() => {
//   return messages.value.filter(msg => {
//     const matchSender = selectedSenderId.value === '' || msg.senderId === selectedSenderId.value;
//     const matchReceiver = selectedReceiverId.value === '' || msg.receiverId === selectedReceiverId.value;
//     return matchSender && matchReceiver;
//   });
// });

// 新增：筛选方法
const handleFilter = async () => {
  isLoading.value = true;
  isSearch.value = true;
  try {
    const res = await axios.post('/messages/query', {
      senderId: selectedSenderId.value || undefined,
      receiverId: selectedReceiverId.value || undefined
    });
    isLoading.value = false;
    messages.value = res.data.data;
    pagination.value.total = messages.value.length;
    // message.success('筛选成功');
  } catch (err) {
    console.error('筛选失败:', err);
    isLoading.value = false;
  }
};

// 新增：重置筛选方法
const resetFilter = async () => {
  selectedSenderId.value = '';
  selectedReceiverId.value = '';
  isSearch.value = false;
  await fetchMessages();
};

// 修改：分页逻辑
const handleTableChange = (pag: Pagination) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchMessages();
  } else {
    handleFilter()
  }
};

// 修改：获取消息列表
const fetchMessages = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/messages/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    messages.value = res.data.data.list;
    console.log('Fetched messages:', messages.value);
    if (messages.value.length === 0 && pagination.value.current > 1) {
      pagination.value.current = pagination.value.current - 1;
      fetchMessages();
    }
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

// 显示修改弹窗
const showModal = (record: Message) => {
  if (record) {
    open.value = true;
    MessageDis.value = {
      messageId: record.messageId,
      senderId: record.senderId,
      receiverId: record.receiverId,
      jobId: record.jobId,
      content: record.content,
      isRead: record.isRead === 1, // 将整数值转换为布尔值
      sentAt: dayjs(record.sentAt),
    };
    console.log('record:', record);
  } else {
    console.error('Invalid record passed to showModal:', record);
  }
};
const addMessage = () => {
  open.value = true;
  MessageDis.value = {
    messageId: 0,
    senderId: undefined,
    receiverId: undefined,
    jobId: undefined,
    content: '',
    isRead: false,
    sentAt: '',
  };
};
const handleOk = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 500);

  // 如果日期为空，则填充当前日期
  if (!MessageDis.value.sentAt) {
    MessageDis.value.sentAt = dayjs();
  }

  axios.post('/messages/update', {
    messageId: MessageDis.value.messageId,
    senderId: MessageDis.value.senderId,
    receiverId: MessageDis.value.receiverId,
    jobId: MessageDis.value.jobId,
    content: MessageDis.value.content,
    isRead: MessageDis.value.isRead ? 1 : 0,
    sentAt: formatDate(MessageDis.value.sentAt),
  }).then(res => {
    if (res.data.code === 200) {
      MessageDis.value = {
        messageId: 0,
        senderId: undefined,
        receiverId: undefined,
        jobId: undefined,
        content: '',
        isRead: false,
        sentAt: '',
      };
      if (!isSearch.value) {
        fetchMessages();
      } else {
        handleFilter();
      }
      message.success(res.data.message);
    }
  }).catch(() => {
    message.error('添加消息失败，请稍后重试');
  });
};

// const updateMessage = () => {
//   confirmLoading.value = true;
//   setTimeout(() => {
//     confirmLoading.value = false;
//   }, 500);
//   console.log("1234" + MessageDis.value);
//   axios.post('/messages/update', {
//     messageId: MessageDis.value.messageId,
//     senderId: MessageDis.value.senderId, // 确保发送的是ID
//     receiverId: MessageDis.value.receiverId, // 确保发送的是ID
//     jobId: MessageDis.value.jobId, // 确保发送的是ID
//     content: MessageDis.value.content,
//     isRead: MessageDis.value.isRead ? 1 : 0, // 将布尔值转换为整数
//     sentAt: formatDate(MessageDis.value.sentAt),
//   }).then(res => {
//     open.value = false;
//     MessageDis.value = {
//       messageId: 0,
//       senderId: undefined,
//       receiverId: undefined,
//       jobId: undefined,
//       content: '',
//       isRead: false,
//       sentAt: '',
//     };
//     if (!isSearch.value) {
//       // 修改：刷新当前页数据
//       fetchMessages();
//     } else {
//         handleFilter()
//     }
//     if (res.data.code === 200) {
//       message.success('更新消息信息成功');
//     } else {
//       message.error('更新消息信息失败');
//     }
//   }).catch(err => {
//     console.error('更新消息失败:', err);
//     message.error('更新消息失败，请稍后重试');
//   });
// };

// 修改：删除消息后刷新当前页数据
const deleteMessage = (record: Message) => {
  axios.post('/messages/delete', {
    messageId: record.messageId
  }).then(() => {
    if (!isSearch.value) {
      fetchMessages();
    } else {
      handleFilter()
    }
    if (messages.value.length === 0) {
      pagination.value.current = pagination.value.current - 1;
      handleFilter();
    }
    message.success('删除消息信息成功');
  }).catch(() => {
    message.error('删除消息失败，请稍后重试');
  });
};

// 搜索逻辑
// const handleSearch = () => {
//   isLoading.value = true;
//   console.log('搜索消息信息:', searchKeyword.value);
//   axios.post('/messages/query', {
//     content: searchKeyword.value,
//   }).then(res => {
//     if (res.data.code === 200) {
//       isSearch.value = true;
//       pagination.value.total = res.data.data.length;
//       messages.value = res.data.data;
//       console.log('res.data.data', res.data.data);
//       console.log('res.data.data.list', res.data.data.list);
//       isLoading.value = false;
//       // message.success('搜索消息信息成功');
//     } else {
//       message.error('搜索失败')
//     }
//   }).catch(err => {
//     console.error('搜索失败:', err);
//     isLoading.value = false;
//   });
// };

// 定义消息数据的类型
interface Message {
  messageId: number;
  senderId: number | undefined;
  receiverId: number | undefined;
  jobId: number | undefined;
  content: string;
  isRead: boolean;
  sentAt: string;
}
// 初始化 MessageDis 为一个空对象
const MessageDis = ref<Message>({
  messageId: 0,
  senderId: undefined,
  receiverId: undefined,
  jobId: undefined,
  content: '',
  isRead: false,
  sentAt: '',
});

// 新增用户和职位名称映射
const userMap = ref<{ [key: number]: string }>({});
const jobMap = ref<{ [key: number]: string }>({});

// 获取用户名称映射
const fetchUserNames = async () => {
  try {
    const res = await axios.get('/users/list', {
      params: {
        page: 1,
        size: 100
      }
    });
    if (res.data.code === 200) {
      userMap.value = res.data.data.list.reduce((map: { [key: number]: string }, user: any) => {
        map[user.userId] = user.username;
        return map;
      }, {});
    }
  } catch (err) {
    console.error('获取用户列表失败:', err);
  }
};

// 获取职位名称映射
const fetchJobTitles = async () => {
  try {
    const res = await axios.get('/jobs/list', {
      params: {
        page: 1,
        size: 100
      }
    });
    if (res.data.code === 200) {
      jobMap.value = res.data.data.list.reduce((map: { [key: number]: string }, job: any) => {
        map[job.jobId] = job.title;
        return map;
      }, {});
    }
  } catch (err) {
    console.error('获取职位列表失败:', err);
  }
};

// 用户和职位选项
const userOptions = ref<{ value: number; label: string }[]>([]);
const jobOptions = ref<{ value: number; label: string }[]>([]);

// 获取用户选项
const fetchUserOptions = async () => {
  try {
    const res = await axios.get('/users/list', {
      params: {
        page: 1,
        size: 100
      }
    });
    userOptions.value = res.data.data.list.map((user: any) => ({
      value: user.userId,
      label: user.username
    }));
  } catch (err) {
    console.error('获取用户列表失败:', err);
    message.error('获取用户列表失败');
  }
};

// 获取职位选项
const fetchJobOptions = async () => {
  try {
    const res = await axios.get('/jobs/list', {
      params: {
        page: 1,
        size: 100
      }
    });
    jobOptions.value = res.data.data.list.map((job: any) => ({
      value: job.jobId,
      label: job.title
    }));
  } catch (err) {
    console.error('获取职位列表失败:', err);
    message.error('获取职位列表失败');
  }
};

// 初始化时加载用户和职位选项
onMounted(async () => {
  await fetchUserOptions();
  await fetchJobOptions();
  await fetchUserNames(); // 新增：获取用户名称映射
  await fetchJobTitles(); // 新增：获取职位名称映射
  await fetchMessages();
});

// 修改表格列定义，支持显示名称
const columns = [
  {
    title: '发送者',
    dataIndex: 'senderId',
    customRender: ({ text }: { text: number }) => userMap.value[text] || '未知用户'
  },
  {
    title: '接收者',
    dataIndex: 'receiverId',
    customRender: ({ text }: { text: number }) => userMap.value[text] || '未知用户'
  },
  {
    title: '职位',
    dataIndex: 'jobId',
    customRender: ({ text }: { text: number }) => jobMap.value[text] || '未知职位'
  },
  {
    title: '内容',
    dataIndex: 'content'
  },
  {
    title: '是否已读',
    dataIndex: 'isRead',
    customRender: ({ text }: { text: boolean }) => (text ? '已读' : '未读')
  },
  {
    title: '发送时间',
    dataIndex: 'sentAt',
    customRender: ({ text }: { text: string }) => formatDate(text)
  },
  {
    title: '操作',
    dataIndex: 'action'
  }
];
</script>



